import 'package:banyou_app/app/config/colors.dart';
import 'package:banyou_app/app/widget/app_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';

import '../controllers/dongtai_controller.dart';


import 'package:flutter/material.dart';

import 'package:get/get.dart';

import 'package:webview_flutter/webview_flutter.dart' as webv;
import 'package:webview_flutter/webview_flutter.dart';

class DongtaiView extends GetView<DongtaiController> {
  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          appBar: AppBarWidget(
              showLeading: controller.canGoBack.value,
              leadingCallback: () async {
                if (controller.webViewController != null) {
                  bool a = await controller.webViewController!.canGoBack();
                  if (a) {
                    controller.webViewController!.goBack();
                  } else {
                    controller.webViewController!.reload();
                  }
                }
              },
              titleStr: controller.title.value),
          body: web(),
        ));
  }

  web() {
    return Obx(() => controller.url.value.length > 0
        ? webv.WebView(
            initialUrl: controller.url.value, //需要打开的url

            //是否支持js 默认是不支持的，
            javascriptMode: webv.JavascriptMode.unrestricted,
            gestureNavigationEnabled: true,
            //加载js方法到页面内，js通过此来调用flutter的方法
            javascriptChannels: _loadJavascriptChannel(),
            //路由委托（可以通过在此处拦截url实现JS调用Flutter部分）
            navigationDelegate: (NavigationRequest request) {
              if (request.url.startsWith('servicef')) {
                // Bridge.preventUrl(request.url, _controller);
                Uri service = Uri.parse(request.url);
                Map q = service.queryParameters;
                if (q.isNotEmpty && q.containsKey('url')) {
                  controller.launchURL(Uri.parse(q['url']));
                }
                return NavigationDecision.prevent;
              }

              return NavigationDecision.navigate;
            },

            onWebViewCreated: (web) {
              controller.webViewController = web;
            },
            onProgress: (progress) async {
              print('object');
              print(progress);
            },
            onWebResourceError: (error) {
              print('加载失败');
              print(error);
            },

            onPageFinished: (url) async {
              String title = await controller.webViewController!
                  .runJavascriptReturningResult('document.title');
              print('title=======' + title);
              // controller.canGoBack.value =
              //     await controller.webViewController!.canGoBack();
              // String currentUrl =
              //     await controller.webViewController!.currentUrl() ?? "";
              // controller.canGoBack.value = currentUrl == controller.url.value;
              // print('canGoBack=======' + controller.canGoBack.value.toString());
              // print('currentUrl=======' + currentUrl);

              // controller.title.value = title.length == 0 ? '直约' : title;
            },
          )
        : Container());
  }

  Set<JavascriptChannel> _loadJavascriptChannel() {
    final Set<JavascriptChannel> channels = Set<JavascriptChannel>();
    JavascriptChannel startFunction = JavascriptChannel(
        name: 'startFunction',
        onMessageReceived: (JavascriptMessage message) {
          // _getTitle();

          controller.messageHandle(message);
          // print(jsonDecode(message.message));
        });
    // JavascriptChannel h5JumpNative = JavascriptChannel(
    //     name: 'h5JumpNative',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });
    // JavascriptChannel appJump = JavascriptChannel(
    //     name: 'appJump',
    //     onMessageReceived: (JavascriptMessage message) {
    //       print('获取到方法');
    //       print(message.message);
    //     });

    channels.addAll([
      startFunction,
    ]);
    return channels;
  }
}


// class DongtaiView extends GetView<DongtaiController> {
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: Stack(
//         children: [
//           Positioned.fill(
//               child: Image.asset(
//             'assets/images/背景@2x.png',
//             width: 1.sw,
//             height: 1.sh,
//             fit: BoxFit.cover,
//           )),
//           Positioned.fill(
//             child: SafeArea(
//               child: SingleChildScrollView(
//                 child: Column(
//                   children: [
//                     Container(
//                       padding:
//                           EdgeInsets.symmetric(horizontal: 16, vertical: 20),
//                       child: ListView.separated(
//                           padding: EdgeInsets.zero,
//                           shrinkWrap: true,
//                           physics: NeverScrollableScrollPhysics(),
//                           itemBuilder: (c, i) {
//                             return itemWidget();
//                           },
//                           separatorBuilder: (c, i) {
//                             return Container(
//                               height: 10,
//                             );
//                           },
//                           itemCount: 10),
//                     )
//                   ],
//                 ),
//               ),
//             ),
//           ),
//         ],
//       ),
//     );
//   }

//   itemWidget() {
//     return Container(
//       child: Column(
//         children: [
//           Row(
//             children: [
//               ClipOval(
//                 child: Container(
//                   decoration: const BoxDecoration(
//                     color: ColorConfig.white,
//                     shape: BoxShape.circle,
//                     boxShadow: [
//                       BoxShadow(
//                         color: Color(0xFFE8E8E8),
//                         offset: Offset(8, 8),
//                         blurRadius: 10,
//                         spreadRadius: 1,
//                       ),
//                     ],
//                   ),
//                   padding: EdgeInsets.all(10),
//                   child: Image.asset('assets/images/touxiang.png',
//                       width: 50.w, height: 50.w, fit: BoxFit.cover),
//                 ),
//               ),
//               SizedBox(width: 20),
//               Column(
//                 mainAxisAlignment: MainAxisAlignment.start,
//                 crossAxisAlignment: CrossAxisAlignment.start,
//                 children: [
//                   Row(
//                     children: [
//                       Text(
//                         '迪丽热巴',
//                         style: TextStyle(
//                             fontSize: 18.sp,
//                             fontWeight: FontWeight.bold,
//                             color: ColorConfig.text_label),
//                       ),
//                       SizedBox(width: 3),
//                       Container(
//                         padding: EdgeInsets.symmetric(horizontal: 3),
//                         decoration: BoxDecoration(
//                           color: Color(0xFFF8DCEC),
//                           borderRadius: BorderRadius.all(Radius.circular(8)),
//                         ),
//                         child: Row(
//                           children: [
//                             Image.asset(
//                               'assets/images/nv.png',
//                               width: 16.w,
//                             ),
//                             Text('21',
//                                 style: TextStyle(
//                                     fontSize: 10.sp, color: Color(0xFFEB6DAF))),
//                           ],
//                         ),
//                       )
//                     ],
//                   ),
//                   SizedBox(height: 5),
//                   Text(
//                     '2小时前 I 1.5km',
//                     style: TextStyle(fontSize: 12.sp, color: Color(0xFF959595)),
//                   ),
//                 ],
//               )
//             ],
//           ),
//           SizedBox(height: 10),
//           Container(
//             width: 1.sw,
//             child: Text(
//               '2小时前 I 1.5km',
//               style: TextStyle(fontSize: 14.sp, color: ColorConfig.text_label),
//             ),
//           ),
//           SizedBox(height: 10),
//           // 图片
//           // 在看
//           Row(
//             children: [
//               Text(
//                 '122人在看',
//                 style: TextStyle(fontSize: 12.sp, color: Color(0xFF959595)),
//               ),
//               SizedBox(width: 10),
//               Row(
//                 children: [
//                   Image.asset(
//                     'assets/images/组 15@2x.png',
//                     width: 18.w,
//                   ),
//                   SizedBox(width: 5),
//                   Text('3人留言',
//                       style:
//                           TextStyle(fontSize: 14.sp, color: Color(0xFF959595))),
//                 ],
//               ),
//             ],
//           )
//         ],
//       ),
//     );
//   }
// }
